require(["config"], function() {
	require(["jquery", "template", "header", "zoom","carousel", "cookie"], function($, template) {
		function Detail() {
			this.render();
		}

		Detail.prototype = {
			constructor: Detail,
			render: function(){
				$.ajax("http://rap2api.taobao.org/app/mock/87071/api/detail")
				.done($.proxy(this.handleDate,this));				
			},
			//处理ajax得到的数据
			handleDate: function(data){			
				var	data = data.res_body.data;
				var html = template("detail-template",data);
				$(".detail-container .wrap").html(html);
				//放大镜
				this.zoom();
				//添加监听事件
				this.addListener();
			},	
			// 放大镜效果
			zoom: function() {
				$(".middle-zoom").elevateZoom({
					gallery:'small', 
					cursor: 'pointer', 
					galleryActiveClass: 'active'
				});
			},
			//给数量加减和添加购物车绑定监听事件
			addListener:function(){
				//加减
				$(".qty-block").click(function(event){
					var src = event.target;
					if($(src).attr("class") === "qty-sub"){
						var i = $("#qty").val();						
						if(i>=2){
							i--;
							$("#qty").val(i);
						}
						else
							return;
					}
					else if($(src).attr("class") === "qty-add"){
						var i = $("#qty").val();
						var temp = Number($(".count em").text());
						if(i<temp){
							i++;
							$("#qty").val(i);
						}
						return;
					}
					return false;
				});
				//添加购物车
				$(".add-to-cart").click(this.addCartHandle);
			},
			//处理添加购物车事件
			addCartHandle:function(){
				//获取当前选购商品的信息
				var currentProduct = {
					id: $(".prod_id").text(),
					title:$(".ename").text()+$(".cname").text(),
					img:$("#small .small-img img").attr("src"),
					weight:$(".prod_weight").text(),
					price:($(".rmb-price").text()).slice(1),
					amount:$("#qty").val(),
					country:$(".way").text(),
					tariff:$(".price").text()
				}
				console.log(currentProduct);
				$.cookie.json = true;
				var products = $.cookie("cart") || [];
				var has = products.some(function(prod){//判断购物车是否已存在该商品
					if(prod.id == currentProduct.id){
						prod.amount++;
						return true;
					}
					return false;
				});
				if(!has)//未选购
					products.push(currentProduct);
				//保存购物车：存回cookie
				$.cookie("cart",products,{expires:10,path:"/"});				
				return false;
			}
		}

		new Detail();
	});
});